<template>
  <div class="app-container">
    <div class="filter-container">
      <div>
      <el-select
          v-model="listQuery.searchKey2"
          style="width: 200px"
          class="filter-item"
          placeholder="申报标题"
          @change="searchAndSort"
        >
          <el-option
            v-for="item in declareOptions"
            :key="item.key"
            :label="item.label"
            :value="item.key"
          />
      </el-select>
        <el-input
          v-model="listQuery.searchKey1"
          placeholder="项目名称"
          style="width: 200px"
          class="filter-item"
        />
        <el-select
          v-model="listQuery.searchKey3"
          style="width: 200px"
          class="filter-item"
          placeholder="项目状态"
        >
          <el-option
            v-for="item in projectStatusOptions"
            :key="item.key"
            :label="item.label"
            :value="item.key"
          />
        </el-select>
        <el-button
          class="filter-item"
          type="primary"
          icon="el-icon-search"
          @click="searchAndSort"
        >
          查找
        </el-button>
      </div>
        <div>
          <el-button :loading="downloadLoading" style="margin:0 0 20px 20px;" type="primary" icon="el-icon-document" @click="handleDownload">
            导出 Excel
          </el-button>
        </div>
      </div>

      <el-table
        :key="tableKey"
        v-loading="listLoading"
        :data="list"
        border
        fit
        highlight-current-row
        style="width: 100%"
      >
      <el-table-column label="申报标题" min-width="50px" align="center">
          <template slot-scope="{ row }">
            <span class="link-type">{{ row.projectDeclareName }}</span>
          </template>
        </el-table-column>
        <el-table-column label="项目编号" min-width="50px" align="center">
          <template slot-scope="{ row }">
            <span class="link-type">{{ row.projectId }}</span>
          </template>
        </el-table-column>
        <el-table-column label="项目名称" min-width="50px" align="center">
          <template slot-scope="{ row }">
            <span class="link-type">{{ row.projectName }}</span>
          </template>
        </el-table-column>
        <el-table-column label="课题组" min-width="50px" align="center">
          <template slot-scope="{ row }">
            <span class="link-type">{{ row.projectGroupName }}</span>
          </template>
        </el-table-column>
        <el-table-column label="负责人" min-width="50px" align="center">
          <template slot-scope="{ row }">
            <span class="link-type">{{ row.projectOwnerName }}</span>
          </template>
        </el-table-column>
        <el-table-column label="所属部门" min-width="50px" align="center">
          <template slot-scope="{ row }">
            <span class="link-type">{{ row.projectDepartment }}</span>
          </template>
        </el-table-column>
        <el-table-column label="负责人电话" min-width="50px" align="center">
          <template slot-scope="{ row }">
            <span class="link-type">{{ row.projectOwnerPhone }}</span>
          </template>
        </el-table-column>
        <el-table-column label="项目状态" min-width="50px" align="center">
          <template slot-scope="{ row }">
            <span class="link-type">{{ row.projectStatus }}</span>
          </template>
        </el-table-column>
        <el-table-column label="开题报告书" min-width="50px" align="center">
          <template slot-scope="{ row }">
            <el-button
                v-if="row.projectAttachFileName"
                size="mini"
                type="primary"
                @click="$router.push(`/project/view/${row.id}`)"
            >
              <i class="el-icon-document" />
            </el-button>
          </template>
        </el-table-column>
        <el-table-column label="立项报告书" min-width="50px" align="center">
          <template slot-scope="{ row }">
            <el-button
              v-if="row.projectAttachFileName"
              size="mini"
              type="primary"
              @click="$router.push(`/project/view/${row.id}`)"
            >
              <i class="el-icon-document" />
            </el-button>
          </template>
        </el-table-column>
        <el-table-column label="中期报告书" min-width="50px" align="center">
          <template slot-scope="{ row }">
            <el-button
              v-if="row.projectMidReportName"
              size="mini"
              type="primary"
              @click="$router.push(`/project/report/view/${row.id}`)"
            >
              <i class="el-icon-document" />
            </el-button>
          </template>
        </el-table-column>
        <el-table-column label="结项报告书" min-width="50px" align="center">
          <template slot-scope="{ row }">
            <el-button
              v-if="row.projectFinalReportName"
              size="mini"
              type="primary"
              @click="$router.push(`/project/report/view/${row.id}`)"
            >
              <i class="el-icon-document" />
            </el-button>
          </template>
        </el-table-column>
        <el-table-column label="当前处理" min-width="50px" align="center">
          <template slot-scope="{ row }">
            <span class="link-type">{{ row.projectInformationCheckStatus !== "立项审查通过"? row.projectInformationCheckStatus : row.projectCheckStatus }}</span>
          </template>
        </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        width="230"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="{ row, $index }">
          <el-button
            size="mini"
            type="success"
            @click="$router.push(`/project/view/${row.id}`)"
          >
            查看
          </el-button>
          <el-button
            v-if="isEdit(row.projectStatus, row.projectInformationCheckStatus) && checkPermission(['项目信息：更新'])"
            type="primary"
            size="mini"
            @click="$router.push(`/project/edit/${row.id}`)"
          >
            编辑
            <i class="el-icon-edit"></i>
          </el-button>
          <el-button
            v-if="row.projectStatus === '项目未立项' && checkPermission(['项目信息：删除'])"
            size="mini"
            type="danger"
            @click="handleDelete(row, $index)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="listQuery.pageIndex"
      :limit.sync="listQuery.limit"
      @pagination="getList"
    />
  </div>
</template>

<script>
import { searchThree } from "@/utils";
import Pagination from "@/components/Pagination";
import { fetchProjectList, deleteProject } from '@/api/project';
import projectStatus from "@/data/projectStatus";
import { checkPermission } from '@/utils/permission';

export default {
  name: "projectList",
  components: { Pagination },
  filters: {
    typeFilter(type) {
      return calendarTypeKeyValue[type];
    },
  },
  data() {
    return {
      tableKey: 0,
      totalList: null,
      list: null,
      total: 0,
      listLoading: false,
      downloadLoading: false,
      listQuery: {
        pageIndex: 1,
        limit: 10,
        searchField1: "projectName",
        searchKey1: "",
        searchField2: "projectDeclareName",
        searchKey2: "",
        searchField3: "projectStatus",
        searchKey3: "",
      },
      declareOptions: [],
      projectStatusOptions: projectStatus,
    };
  },
  created() {
    this.getList();
  },
  methods: {
    checkPermission,
    getList() {
      this.listLoading = true;
      fetchProjectList().then((res) => {
        this.totalList = res.data;
        this.totalList.forEach(item => {
            if(item.projectCheckStatus) {
              if(item.projectCheckStatus === "提交项目结项报告") {
                item.projectCheckStatus = "项目中检审批通过";
              } else if(item.projectCheckStatus === "项目已结项") {
                item.projectCheckStatus = "项目结项审批通过";
              }

            }
        });
        this.getDeclareOptions();
        this.handleFilter();

        this.listLoading = false;
      });
    },
    handleFilter() {
      const result=searchThree(this.totalList, this.listQuery);
      this.list = result.data;
      this.total=result.total;
    },
    getDeclareOptions() {
        const options = [];
        this.totalList.forEach(item => {
            options.push({key: item.projectDeclareName, label: item.projectDeclareName})
        });
        this.declareOptions = [...new Set(options)];
      },
    searchAndSort() {
      this.listQuery.pageIndex = 1;
      this.handleFilter();
    },
    isEdit(status, infoCheckStatus) {
      if ((['项目未立项'].includes(status) && ['科研处立项预审中', '科研处立项预审驳回', '专家立项伦理审查驳回', '领导立项总审查驳回',
       '财务立项审查驳回'].includes(infoCheckStatus))) {
        return true;
      }
      return false;
    },
    handleDownload() {
      this.downloadLoading = true
      import('@/components/ExportExcel/Export2Excel').then(excel => {
        const tHeader = ['序号', '申报标题', '项目编号', '项目名称', '课题组', '负责人', '所属部门', '负责人电话', '项目状态'];
        const filterVal = ['id', 'projectDeclareName', 'projectId', 'projectName', 'projectGroupName', 'projectOwnerName', 'projectDepartment', 'projectOwnerPhone', 'projectStatus']
        const list = this.totalList
        const data = this.formatJson(filterVal, list)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: '项目列表',
          autoWidth: true,
          bookType: 'xlsx'
        })
        this.downloadLoading = false
      })
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    },
    handleDelete(row, index) {
      this.$confirm(`是否确定删除 "${row.projectName}"`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(async () => {
        //请求接口
        deleteProject(row.id)
          .then((res) => {
            if (res.data) {
              this.$message({
                type: "success",
                message: "删除成功!",
              });
              //重新获取
              this.getList();
            } else {
              this.$message({
                message: "项目删除失败",
                type: "error",
              });
            }
          })
          .catch((err) => {
            this.$message({
              message: "项目删除失败",
              type: "error",
            });
          });
      });
    },
  },
};
</script>
<style lang="scss" scoped>
@import "~@/styles/mixin.scss";

.filter-container {
  display: flex;
  justify-content: space-between;
}
</style>
